package com.newflypig.jblog.controller.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.BlogCommon;
import com.newflypig.jblog.service.IArticleService;
import com.newflypig.jblog.util.FreemarkerUtil;

public class RSSInterceptor implements HandlerInterceptor {

	@Autowired
	private IArticleService articleService;

	@Autowired
	private BlogCommon blogCommon;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// 如果对文章有POST操作，则更新一次RSS
		if ("POST".equalsIgnoreCase(request.getMethod())) {
			String templateFilePath = request.getServletContext().getRealPath("/WEB-INF/views/ftl");
			String outputFilePath = request.getServletContext().getRealPath("/rss.xml");

			new Thread(() -> {
				List<Article> articleList = this.articleService.findAllForRSS();

				try {
					new FreemarkerUtil().generateRSS(articleList, blogCommon, templateFilePath, outputFilePath);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
		}

	}

}
